import axios from "axios";
import config from "@/config";

const request = {};
//支持的请求方法
const methods = [
  "get",
  "head",
  "post",
  "put",
  "delete",
  "options",
  "patch",
  "form",
];

const service = axios.create({
  timeout: 10000,
  baseURL: config.baseURL || "",
});

//添加请求拦截器
service.interceptors.request.use(
  (config) => {
    return config;
  },
  (error) => {
    console.log(error); // for debug
    return Promise.reject(error);
  }
);

// 添加响应拦截器
service.interceptors.response.use(
  (response) => {
    return response;
  },
  (error) => {
    console.log("err" + error); // for debug
  }
);

/**
 * @description: 简单的请求方法
 * @param {*} url
 * @param {*} method
 * @param {*} data
 * @param {*} isFile
 */
function baseRequest(url, method, data, { isFile = false }) {
  return new Promise((resolve, reject) => {
    let reqData = {
        method,
        url,
      },
      req = null;
    if (method == "get") {
      reqData.params = data;
      req = service.request(reqData);
    } else {
      reqData.data = data;
      req = service.request(reqData);
    }
    req
      .then((res) => {
        if (isFile) resolve(res.data);
        else if (res.status === 200 && res.data.code === 200) resolve(res.data);
        else {
          reject(res.data.msg || "系统错误");
        }
      })
      .catch(() => {
        reject("请求失败");
      });
  });
}

methods.forEach(
  (method) =>
    (request[method] = (url, data = {}, options = {}) =>
      baseRequest(url, (method = "get"), data, options))
);

export default Request;
